/** markDown标记插件 */
import { NormalToolbar } from 'md-editor-rt';

interface MarkExtensionProp {
  editorId: string;
  onChange: (text: string) => void;
}

const MarkExtension = ({ editorId, onChange }: MarkExtensionProp) => {
  const markHandler = () => {
    // 获取输入框
    const textarea = document.querySelector(`#${editorId}-textarea`) as HTMLTextAreaElement;
    // 获取选中的内容
    const selection = window.getSelection()?.toString();
    // 获取鼠标位置
    const endPoint = textarea.selectionStart;

    // 生成标记文本
    const markStr = `@${selection}@`;

    // 根据鼠标位置分割旧文本
    // 前半部分
    const prefixStr = textarea.value.substring(0, endPoint);
    // 后半部分
    const suffixStr = textarea.value.substring(endPoint + (selection?.length || 0));

    onChange(`${prefixStr}${markStr}${suffixStr}`);

    setTimeout(() => {
      textarea.setSelectionRange(endPoint, markStr.length + endPoint);
      textarea.focus();
    }, 0);
  };

  return (
    <NormalToolbar
      title="mark"
      onClick={markHandler}
      trigger={
        <svg
          className="icon"
          viewBox="0 0 1024 1024"
          version="1.1"
          xmlns="http://www.w3.org/2000/svg"
          width="22"
          height="22"
        >
          <path
            d="M816.64 156.16l-248.32 166.4c-33.28 23.04-79.36 23.04-112.64 0L207.36 156.16C174.08 133.12 128 156.16 128 197.12V768c0 84.48 69.12 153.6 153.6 153.6h460.8c84.48 0 153.6-69.12 153.6-153.6V197.12c0-40.96-46.08-64-79.36-40.96zM793.6 768c0 28.16-23.04 51.2-51.2 51.2H281.6c-28.16 0-51.2-23.04-51.2-51.2V294.4l168.96 112.64c69.12 46.08 158.72 46.08 227.84 0l168.96-112.64V768z"
            fill="#515151"
          />
        </svg>
      }
    />
  );
};

export default MarkExtension;
